package com.free.resolver;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.free.annotation.LoginUser;
import com.free.entity.UserEntity;
import com.free.interceptor.AuthorizationInterceptor;
import com.free.service.UserService;

/**
 * 
* @ClassName: LoginUserHandlerMethodArgumentResolver 
* @Description: TODO(有@LoginUser注解的方法参数，注入当前登录用户) 
* @author wujie
* @email 602991693@qq.com 
* @date 2017年8月31日 下午2:10:56 
*
 */
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver{
	private UserService userService;
	
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterType().isAssignableFrom(UserEntity.class) && parameter.hasParameterAnnotation(LoginUser.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
			NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
		//获取用户id
		Object object = request.getAttribute(AuthorizationInterceptor.LOGIN_USER_KEY, RequestAttributes.SCOPE_REQUEST);
		if(object == null){
			return null;
		}
		//获取用户信息
		UserEntity user = userService.queryObject((Long)object);
		return user;
	}

}
